//
//  CUser.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CUser.h"

@implementation CUser

static CUser *g_Instance = nil;

@synthesize U_AID;
@synthesize U_City;
@synthesize U_Nick;
@synthesize U_Pas;
@synthesize U_LogIn;
@synthesize U_Token;
@synthesize U_Session;
@synthesize U_UrlIcon;
@synthesize U_Icon;
@synthesize U_Name;
@synthesize U_Mail;
@synthesize U_CurCity;
@synthesize U_QqOn;
@synthesize U_SinaOn;
@synthesize U_RenrenOn;
@synthesize U_DisedOn;
@synthesize U_FpubOn;
@synthesize U_OsOn;
@synthesize U_DisNum;
@synthesize U_FrdNum;
@synthesize U_PdtNum;

@synthesize m_AddrInfo;
@synthesize m_SelfPosition;

//@synthesize m_Data;
@synthesize m_RootPath;
@synthesize m_FriendPath;
@synthesize m_FavoritePath;
@synthesize m_FriendTable;
@synthesize m_FavoriteTable;
@synthesize m_UploadPath;
@synthesize m_UploadTable;
@synthesize m_DraftPath;

//action
@synthesize m_IsIconLoad;
@synthesize m_IconOpID;
@synthesize m_IconView;
@synthesize m_UCommand;
@synthesize m_Action;
@synthesize m_Target;

//数据请求
@synthesize m_NetRequest;

//临时
@synthesize m_UType;

//favorites
@synthesize m_FavoriteCnt;
@synthesize m_NetFavosCnt;

//friends
@synthesize m_FriendCnt;
@synthesize m_NetFrdCnt;

//timer
@synthesize m_HeartBeat;

+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (nil == g_Instance)
        {
            g_Instance = [super allocWithZone:zone];
        }
    }
    
    return g_Instance;
}

+(CUser*)DefaultUser
{
    if (nil == g_Instance)
    {
        g_Instance = [[CUser alloc] init];
    }
    
    return g_Instance;
}

+(void)DestroyUser
{
    [g_Instance release];
    g_Instance = nil;
}

- (id)init
{
    self = [super init];
    if (self) 
    {
        // Initialization code here.
        m_NetRequest = [[CNetWorkRequest alloc] init];
        m_NetRequest.m_Delegate = self;
        m_HeartBeat = nil;
        
        m_AddrInfo = [[CAddrInfo alloc] init];
        
        [self ResetUser];
    }
    
    return self;
}

-(void)SetUserWithArr:(NSArray*)arr
{
    if (arr)
    {
        int nCnt = 0;
        id  objc = nil;
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_AID = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_LogIn = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_QqOn = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_SinaOn  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_RenrenOn  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        //self.U_DisedOn = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        //self.U_FpubOn = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        //self.U_OsOn = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_FrdNum = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_PdtNum = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_DisNum = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_City = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Nick = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Pas = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Token = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Session = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_UrlIcon = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Icon = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Name = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_Mail = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.U_CurCity = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
    }
}

-(void)ResetUser
{
    self.m_UType    = Visitor;
    self.U_AID      = [NSNumber numberWithLong:0];
    self.U_City     = nil;
    self.U_Name     = @"好吃客";
    self.U_Nick     = @"好吃客";
    self.U_Pas      = @"000000";
    self.U_LogIn    = [NSNumber numberWithLong:0];
    self.U_Token    = @"000000";
    self.U_Session  = @"000000";
    self.U_UrlIcon  = @"www";
    self.U_Icon     = nil;
    self.U_Mail     = @"000000";
    self.U_CurCity  = @"世界";
    self.U_QqOn     = [NSNumber numberWithLong:0];
    self.U_SinaOn   = [NSNumber numberWithLong:0];
    self.U_RenrenOn = [NSNumber numberWithLong:0];
    self.U_DisedOn  = [NSNumber numberWithLong:1];
    self.U_FpubOn   = [NSNumber numberWithLong:1];
    self.U_OsOn     = [NSNumber numberWithLong:1];
    self.U_FrdNum   = [NSNumber numberWithLong:0];
    self.U_PdtNum   = [NSNumber numberWithLong:0];
    self.U_DisNum   = [NSNumber numberWithLong:0];
    
    //self.m_Data   = nil;
    self.m_Action   = nil;
    self.m_Target   = nil;
    self.m_IconOpID = nil;
    self.m_IconView = nil;
    
    self.m_IsIconLoad   = NO;
    self.m_FavoritePath = nil;
    self.m_FriendPath   = nil;
    self.m_RootPath     = nil;
    self.m_FriendTable  = nil;
    self.m_FavoriteTable= nil;
    self.m_UploadPath   = nil;
    self.m_UploadTable  = nil;
    
    m_FavoriteCnt = [[CAscCounter alloc] init];
    [m_FavoriteCnt InitAscWithCount:[self.U_PdtNum longValue] Limit:10];
    m_NetFavosCnt = [[CAscCounter alloc] init];
    [m_NetFavosCnt InitAscWithCount:0 Limit:5];
    
    m_FriendCnt = [[CAscCounter alloc] init];
    [m_FriendCnt InitAscWithCount:[self.U_FrdNum longValue] Limit:10];
    m_NetFrdCnt = [[CAscCounter alloc] init];
    [m_NetFrdCnt InitAscWithCount:0 Limit:5];
    //[self.m_NetRequest.m_UrlConnection cancel];
}

-(void)dealloc
{
    [U_AID release];
    [U_DisedOn release];
    [U_FpubOn release];
    [U_OsOn release];
    [U_QqOn release];
    [U_SinaOn release];
    [U_RenrenOn release];
    [U_LogIn release];
    [U_City release];
    [U_Name release];
    [U_Name release];
    [U_Pas release];
    [U_Token release];
    [U_Session release];
    [U_UrlIcon release];
    [U_Icon release];
    [U_Mail release];
    [U_CurCity release];
    [m_FavoriteTable release];
    [m_FavoritePath release];
    [m_FriendPath release];
    [m_FriendTable release];
    [m_UploadPath release];
    [m_UploadTable release];
    [U_DisNum release];
    [U_FrdNum release];
    [U_PdtNum release];
    
    [m_NetRequest release];
    [m_FriendCnt release];
    [m_NetFavosCnt release];
    [m_NetFrdCnt release];
    
    [m_AddrInfo release];
    
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_IconOpID];
    [m_IconOpID release];
    
    [super dealloc];
}

+(int)CreateUserTable:(NSString*)tablename
{
    NSMutableArray *keys = [NSMutableArray array];
    CKey            *key = nil;
        
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_AID" Primary:YES];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_LogIn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_QqOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_SinaOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_RenrenOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_DisedOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_FpubOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_OsOn" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_FrdNum" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_PdtNum" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"U_DisNum" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"U_City" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"U_Nick" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"U_Pas" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:60 Name:@"U_Token" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:60 Name:@"U_Session" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"U_UrlIcon" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"U_Icon" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"U_Name" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:60 Name:@"U_Mail" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:15 Name:@"U_Latitude" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:15 Name:@"U_Longtitude" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"U_CurCity" Primary:NO];
    [keys addObject:key];
    [key release];
    
    return [[CDBManager ScheduledShareInstance] CreateTable:@"Users" Keys:keys];
}
+(NSArray*)GetLimitUsers:(NSString*)where Offset:(int)offset Limit:(int)limit
{
    NSArray *keys = [NSArray arrayWithObjects:@"*", nil];
    return [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:@"Users" Keys:keys Offset:offset Limit:limit Column:User_Properties_Num Condition:where];
}

+(NSInteger)GetUserCount:(NSString *)where
{
    return [[CDBManager ScheduledShareInstance] GetRecordTotal:@"Users" Condition:where Key:@"U_AID"];
}

+(int)UpadteUserInfo:(NSString*)where Keys:(NSArray*)keys
{
    return [[CDBManager ScheduledShareInstance] UpdateRecordInfo:@"Users" Keys:keys Condition:where];
}

+(int)RemoveUser:(NSString*)where
{
    return [[CDBManager ScheduledShareInstance] DeleteRecord:@"Users" Condition:where];
}

-(int)SaveUser
{
    NSMutableArray *keys = [NSMutableArray array];
    CKey            *key = nil;
    
    key = [[CKey alloc] initWithType:1 Value:self.U_AID Name:@"U_AID"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_LogIn Name:@"U_LogIn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_QqOn Name:@"U_QqOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_SinaOn Name:@"U_SinaOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_RenrenOn Name:@"U_RenrenOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_DisedOn Name:@"U_DisedOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_FpubOn Name:@"U_FpubOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_OsOn Name:@"U_OsOn"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_FrdNum Name:@"U_FrdNum"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_PdtNum Name:@"U_PdtNum"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.U_DisNum Name:@"U_DisNum"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_City Name:@"U_City"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Nick Name:@"U_Nick"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Pas Name:@"U_Pas"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Token Name:@"U_Token"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Session Name:@"U_Session"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_UrlIcon Name:@"U_UrlIcon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Icon Name:@"U_Icon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Name Name:@"U_Name"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_Mail Name:@"U_Mail"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.U_CurCity Name:@"U_CurCity"];
    [keys addObject:key];
    [key release];
    
    return [[CDBManager ScheduledShareInstance] InsertNewRecordToTable:@"Users" Keys:keys];
}

-(int)SaveIcon:(NSData*)data
{
    if (![[NSFileManager defaultManager] createFileAtPath:self.U_Icon contents:data attributes:nil])
    {
        NSLog(@"save user's icon of product failed!");
        return 1;
    }
    
    return 0;
}


-(NSData*)GetUserIcon
{
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:self.U_Icon];
    if (nil == data)
    {
        [self DownloadUserIcon];
    }
    
    return data;
}

-(int)DownloadUserIcon
{
    if (!m_IsIconLoad)
    {
        m_IsIconLoad = YES;
        NSLog(@"%@", self.U_UrlIcon);
        self.m_IconOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:self.U_UrlIcon Sponsor:self PostData:nil TimeOut:10 Data:[NSNumber numberWithShort:0] MType:Get UserInfo:nil];
    }
    
    return 0;
}

-(void)GetCurUser
{
    NSArray *ret = [CUser GetLimitUsers:@"U_LogIn == 1" Offset:0 Limit:1];
    if ([ret count] > 0)
    {
        NSArray *arr = [ret objectAtIndex:0];
        [self SetUserWithArr:arr];
        
        self.m_FriendTable   = [NSString stringWithFormat:@"%@_friend", self.U_Name];
        self.m_FavoriteTable = [NSString stringWithFormat:@"%@_favorite", self.U_Name];
        self.m_RootPath      = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), self.U_Name];
        self.m_FavoritePath  = [NSString stringWithFormat:@"%@/favorite", self.m_RootPath];
        self.m_UploadTable   = [NSString stringWithFormat:@"%@_upload", self.U_Name];
        self.m_UploadPath    = [NSString stringWithFormat:@"%@/upload", self.m_RootPath];
        self.m_DraftPath     = [NSString stringWithFormat:@"%@/draft", self.m_RootPath];
        self.m_UType = Logined;
        
        [self StartHeartBeat];
        [self SendHeartBeat];
    }
}

//heartbeat
-(void)DidReceiveData:(CNetWorkRequest *)request Data:(NSMutableData *)data
{
    [self ReceiveHeartBeat:data];
}

-(void)DidReceiveError:(CNetWorkRequest *)request Error:(NSError *)error
{
    NSLog(@"Send the heartbeat failed!");
}

-(void)DidRectiveTimeout:(CNetWorkRequest *)request
{
    NSLog(@"Send the heartbeat failed because of timeout!");
}

-(void)DidStopRequestNoNet:(CNetWorkRequest *)request
{
    NSLog(@"Send the heartbeat failed because of no network!");
}

-(void)StartHeartBeat
{
    //start hertbeat
    if (!m_HeartBeat && (Logined == self.m_UType))
    {
        m_HeartBeat = [NSTimer scheduledTimerWithTimeInterval:600 target:self selector:@selector(SendHeartBeat) userInfo:nil repeats:NO];
    }
}

-(void)StopHeartBeat
{
    m_HeartBeat = nil;
}

-(void)SendHeartBeat
{
    if (m_HeartBeat)
    {
        NSMutableString *des = [[NSMutableString alloc] initWithCapacity:18];
        [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
        [des appendString:@"&user_mobi_key="];
        [des appendString:self.U_Token];
        [des appendString:@"&"];
        [des appendString:@"user_session_id="];
        [des appendString:self.U_Session];
        [des appendString:@"&"];
        [des appendString:@"Logininfo="];
        [des appendString:self.U_Name];
        [des appendString:@"&"];
        [des appendString:@"op_id="];
        [des appendString:[NSString stringWithFormat:@"%ld", [self.U_AID longValue]]];
        [des appendString:@"&"];
        [des appendString:@"User_pass="];
        [des appendString:self.U_Pas];
        [des appendString:@"&"];
        [des appendString:@"Divtype="];
        [des appendString:[UIDevice currentDevice].model];

        [m_NetRequest SetRequestWithUrl:URL_HEATBEAT Method:Post Value:[des dataUsingEncoding:NSUTF8StringEncoding] IsSynchronous:NO OutTime:30];
        
        NSLog(@"\r\n\r\nSend the heartbeat to server!\r\n\r\n");
        
        [des release];
    }
}

-(void)ReceiveHeartBeat:(NSData*)notification
{
    if ((Logined == self.m_UType) && (m_HeartBeat))
    {
        m_HeartBeat = nil;
        
        NSString     *json = [[NSString alloc] initWithData:notification encoding:NSUTF8StringEncoding];
        NSDictionary *dic  = [json JSONValue];
        
        if (dic)
        {
            NSLog(@"\r\n\r\nheartbeat:%@\r\n\r\n", dic);
            
            int nCode = [[dic objectForKey:@"Msg_error"] intValue];
            if (0 == nCode)
            {
                long ID = [self.U_AID longValue];
                self.U_AID = [NSNumber numberWithLong:[[dic objectForKey:@"Op_id"] intValue]];
                //token
                self.U_Token = [dic objectForKey:@"User_mobi_key"];
                //session
                self.U_Session = [dic objectForKey:@"User_session_id"];
                
                //save to db
                NSMutableArray *keys = [NSMutableArray array];
                CKey *key = [[CKey alloc] initWithType:1 Value:self.U_AID Name:@"U_AID"];
                [keys addObject:key];
                [key release];
                
                key = [[CKey alloc] initWithType:3 Value:self.U_Token Name:@"U_Token"];
                [keys addObject:key];
                [key release];
                
                key = [[CKey alloc] initWithType:3 Value:self.U_Session Name:@"U_Session"];
                [keys addObject:key];
                [key release];
                
                [CUser UpadteUserInfo:[NSString stringWithFormat:@"U_AID==%ld", ID] Keys:keys];
                
                //NSLog(@"Receive the heartbeat from server!");
            }
            else 
            {
                NSLog(@"\r\n\r\nServer refuses my heartbeat!(%@)\r\n\r\n", [dic objectForKey:@"Msg"]);
            }
        }
        else 
        {
            NSLog(@"\r\n\r\nReceive the wrong heatbeat(%@)!\r\n\r\n", json);
        }
        
        [self StartHeartBeat];
        
        [json release];
    }
}

-(NSArray*)GetCurUserFavos
{
    if (self.m_FavoriteTable)
    {
        NSArray *rets = [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:self.m_FavoriteTable Keys:[NSArray arrayWithObjects:@"*", nil] Offset:m_FavoriteCnt.m_nOffset Limit:m_FavoriteCnt.m_nLimit Column:Product_Properties_Num Condition:nil];
        [m_FavoriteCnt GetAscNextLimit:m_FavoriteCnt.m_nTotal Cnt:[rets count]];
        
        return rets;
    }
    
    return nil;
}

//get user's favorites from server
-(void)GetCurUserFavosFromSrv
{
    //
}

-(NSArray*)GetCurUserFrds
{
    if (self.m_FriendTable && self.m_FriendCnt.m_nLimit > 0)
    {
        NSArray *rets = [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:self.m_FavoriteTable Keys:[NSArray arrayWithObjects:@"*", nil] Offset:m_FriendCnt.m_nOffset Limit:m_FriendCnt.m_nLimit Column:Friend_Properties_Num Condition:nil];
        [m_FavoriteCnt GetAscNextLimit:m_FriendCnt.m_nTotal Cnt:[rets count]];
        
        return rets;
    }
    
    return nil;
}

//get user's friends from server
-(void)GetCurUserFrdsFromSrv
{
    if (Logined == self.m_UType)
    {
        self.m_UCommand = GetFrds;
        
        NSMutableString *des = [NSMutableString stringWithCapacity:6];
        
        [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
        [des appendFormat:@"&mobikey=%@", self.U_Token];
        [des appendFormat:@"&sessionid=%@", self.U_Session];
        [des appendFormat:@"&action=%@", @"showfriend"];
        [des appendFormat:@"&cursor=%d", self.m_NetFrdCnt.m_nOffset];
        [des appendFormat:@"&offset=%d", self.m_NetFrdCnt.m_nLimit];
        
        [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_MYFRIEND Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:self.m_UCommand] MType:Post UserInfo:nil];
    }
}

//client request
//user register successful
-(void)GetServerRegisterResult:(NSDictionary*)data
{
    NSError *error = nil;
    int     ncode  = [[data objectForKey:@"Msg_error"] intValue];
    
    if (0 == ncode)
    {
        self.m_UType = Logined;
        
        //create user's root directory(user's loginname)
        self.m_RootPath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), self.U_Name];
        self.U_Icon     = [NSString stringWithFormat:@"%@/%@_icon.jpg", self.m_RootPath, self.U_Name];
        if ([[NSFileManager defaultManager] createDirectoryAtPath:self.m_RootPath withIntermediateDirectories:NO attributes:nil error:&error])
        {
            //create user's fridendpath
            self.m_FriendPath = [NSString stringWithFormat:@"%@/friend", self.m_RootPath];
            if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_FriendPath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's friendpath for %@ failed(%@)!", self.U_Name, error.domain);
            }
            //create user's favoritepath
            self.m_FavoritePath = [NSString stringWithFormat:@"%@/favorite", self.m_RootPath];
            if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_FavoritePath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's favoritepath for %@ failed(%@)!", self.U_Name, error.domain);
            }
            //create user's uploadpath
            self.m_UploadPath = [NSString stringWithFormat:@"%@/upload", self.m_RootPath];
            if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_UploadPath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's uploadpath for %@ failed(%@)!", self.U_Name, error.domain);
            }
            //create user's draft
            self.m_DraftPath = [NSString stringWithFormat:@"%@/draft", self.m_RootPath];
            if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_DraftPath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's draft for %@ failed(%@)!", self.U_Name, error.domain);
            } 
            //info of draft
            if (![[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/info", self.m_DraftPath] withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's draft'info for %@ failed(%@)!", self.U_Name, error.domain);
            } 
            //image of draft
            if (![[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/imgs", self.m_DraftPath] withIntermediateDirectories:NO attributes:nil error:&error])
            {
                NSLog(@"create user's draft'image for %@ failed(%@)!", self.U_Name, error.domain);
            } 
        }
        else 
        {
            NSLog(@"create rootpath for %@ failed(%@)!", self.U_Name, error.domain);
        }
        
        self.U_AID    = [NSNumber numberWithLong:[[data objectForKey:@"Op_id"] intValue]];
        self.U_Token  = [data objectForKey:@"User_mobi_key"];
        self.U_Session= [data objectForKey:@"User_session_id"];
        self.U_LogIn  = [NSNumber numberWithLong:1];
        
        //开关全部打开
        self.U_DisedOn= [NSNumber numberWithInt:1];
        self.U_FpubOn = [NSNumber numberWithInt:1];
        self.U_OsOn   = [NSNumber numberWithInt:1];
        
        //insert new user into userstable
        if (![self SaveUser])
        {
            //create friend tabale
            self.m_FriendTable = [NSString stringWithFormat:@"%@_friend", self.U_Name];
            if ([CFriend CreateFriendTable:self.m_FriendTable])
            {
                NSLog(@"create user's friendstable failed!");
            }
            //create favorite table
            self.m_FavoriteTable = [NSString stringWithFormat:@"%@_favorite", self.U_Name];
            if ([CProduct CreateProdutTable:self.m_FavoriteTable])
            {
                NSLog(@"create user's favoritetable failed!");
            }
            //create upload table
            self.m_UploadTable = [NSString stringWithFormat:@"%@_upload", self.U_Name];
            if ([CProduct CreateProdutTable:self.m_UploadTable])
            {
                NSLog(@"create user's uploadtable failed!");
            }
        }
        else
        {
            NSLog(@"insert new user into database failed!");
        }
        
        //start heart beat
        [self StartHeartBeat];
    }
}

//user login successful
-(void)GetServerLoginResult:(NSDictionary*)data
{
    NSLog(@"用户登陆成功:%@", data);
    
    int ncode  = [[data objectForKey:@"Msg_error"] intValue];
    
    if (0 == ncode)
    {
        //create user's root directory(user's loginname)
        self.m_RootPath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), self.U_Name];
        //create user's iconpath
        self.U_Icon     = [NSString stringWithFormat:@"%@/%@_icon.jpg", self.m_RootPath, self.U_Name];
        //create user's fridendpath
        self.m_FriendPath = [NSString stringWithFormat:@"%@/friend", self.m_RootPath];
        //create user's favoritepath
        self.m_FavoritePath = [NSString stringWithFormat:@"%@/favorite", self.m_RootPath];
        //create friend tabale
        self.m_FriendTable = [NSString stringWithFormat:@"%@_friend", self.U_Name];
        //create favorite table
        self.m_FavoriteTable = [NSString stringWithFormat:@"%@_favorite", self.U_Name];
        //login
        self.U_LogIn = [NSNumber numberWithLong:1];
        //id
        self.U_AID   = [NSNumber numberWithLong:[[data objectForKey:@"Op_id"] intValue]];
        //nickname
        self.U_Nick  = [data objectForKey:@"user_nicename"];
        //token
        self.U_Token = [data objectForKey:@"User_mobi_key"];
        //session
        self.U_Session = [data objectForKey:@"User_session_id"];
        //city
        self.U_City = [data objectForKey:@"city"];
        //头像的url
        self.U_UrlIcon = [data objectForKey:@"img"];
        //switches
        //self.U_DisedOn = [NSNumber numberWithInt:[[data objectForKey:@"receiveComment"] intValue]];
        //self.U_FpubOn  = [NSNumber numberWithInt:[[data objectForKey:@"receiveFriendArticle"] intValue]];
        //self.U_OsOn    = [NSNumber numberWithInt:[[data objectForKey:@"receiveOS"] intValue]];
        self.U_DisedOn = [NSNumber numberWithInt:1];
        self.U_FpubOn  = [NSNumber numberWithInt:1];
        self.U_OsOn    = [NSNumber numberWithInt:1];
        self.U_SinaOn  = [NSNumber numberWithInt:[[data objectForKey:@"Sina"] intValue]];
        self.U_QqOn    = [NSNumber numberWithInt:[[data objectForKey:@"Penguin"] intValue]];
        self.U_RenrenOn= [NSNumber numberWithInt:[[data objectForKey:@"Renren"] intValue]];
        
        if (Leave == self.m_UType)
        {
            //updata user's state
            NSMutableArray *keys = [NSMutableArray array];
            
            CKey *key = [[CKey alloc] initWithType:1 Value:self.U_LogIn Name:@"U_LogIn"];
            [keys addObject:key];
            [key release];
            
            key = [[CKey alloc] initWithType:3 Value:self.U_Token Name:@"U_Token"];
            [keys addObject:key];
            [key release];
            
            key = [[CKey alloc] initWithType:3 Value:self.U_Session Name:@"U_Session"];
            [keys addObject:key];
            [key release];
            
            [CUser UpadteUserInfo:[NSString stringWithFormat:@"U_AID==%ld", [self.U_AID longValue]] Keys:keys];
        }
        else 
        {
            NSError *error = nil;
            //create user's root directory(user's loginname)
            if ([[NSFileManager defaultManager] createDirectoryAtPath:self.m_RootPath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                //create user's fridendpath
                self.m_FriendPath = [NSString stringWithFormat:@"%@/friend", self.m_RootPath];
                if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_FriendPath withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's friendpath for %@ failed(%@)!", self.U_Name, error.domain);
                }
                //create user's favoritepath
                self.m_FavoritePath = [NSString stringWithFormat:@"%@/favorite", self.m_RootPath];
                if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_FavoritePath withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's favoritepath for %@ failed(%@)!", self.U_Name, error.domain);
                }
                //create user's uploadpath
                self.m_UploadPath = [NSString stringWithFormat:@"%@/upload", self.m_RootPath];
                if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_UploadPath withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's uploadpath for %@ failed(%@)!", self.U_Name, error.domain);
                }
                //create user's draft
                self.m_DraftPath = [NSString stringWithFormat:@"%@/draft", self.m_RootPath];
                if (![[NSFileManager defaultManager] createDirectoryAtPath:self.m_DraftPath withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's draft for %@ failed(%@)!", self.U_Name, error.domain);
                } 
                //info of draft
                if (![[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/info", self.m_DraftPath] withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's draft'info for %@ failed(%@)!", self.U_Name, error.domain);
                } 
                //image of draft
                if (![[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/imgs", self.m_DraftPath] withIntermediateDirectories:NO attributes:nil error:&error])
                {
                    NSLog(@"create user's draft'image for %@ failed(%@)!", self.U_Name, error.domain);
                } 
            }
            else 
            {
                NSLog(@"create rootpath for %@ failed(%@)!", self.U_Name, error.domain);
            }
            
            //insert the new user
            if (![self SaveUser])
            {
                //create friend tabale
                self.m_FriendTable = [NSString stringWithFormat:@"%@_friend", self.U_Name];
                if ([CFriend CreateFriendTable:self.m_FriendTable])
                {
                    NSLog(@"create user's friendstable failed!");
                }
                //create favorite table
                self.m_FavoriteTable = [NSString stringWithFormat:@"%@_favorite", self.U_Name];
                if ([CProduct CreateProdutTable:self.m_FavoriteTable])
                {
                    NSLog(@"create user's favoritetable failed!");
                }
                //create upload table
                self.m_UploadTable = [NSString stringWithFormat:@"%@_upload", self.U_Name];
                if ([CProduct CreateProdutTable:self.m_UploadTable])
                {
                    NSLog(@"create user's uploadtable failed!");
                }
            }
            else
            {
                NSLog(@"insert new user into database failed!");
            }
        }
        
        //start heartbeat
        [self StartHeartBeat];
        
        self.m_UType = Logined;
    }
}

//get products from server
-(CTask*)GetProductsFromServer:(NSString*)data Url:(NSString*)url Command:(UCommand)command Object:(id)object
{
    CTask *error = nil;

    if (/*Logined == self.m_UType*/1)
    {
        self.m_UCommand = command;
        error = [[CDownLoadManager DefaultDownLoadManager] AddTask:url Sponsor:self PostData:[data dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:command] MType:Post UserInfo:object];
    }
    
    return error;
}

//user favorite product
-(NSError*)UserFavoriteProduct:(NSString*)data
{
    NSLog(@"<========向服务器发送收藏:%@", data);
    
    NSError *error = nil;
    
    if (Logined == self.m_UType)
    {
        self.m_UCommand = FavoriteP;
        [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_FAVORITE Sponsor:self PostData:[data dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:self.m_UCommand] MType:Post UserInfo:nil];
    }
    else 
    {
        error = [NSError errorWithDomain:@"未登陆用户，请登陆。" code:1 userInfo:nil];
    }
    
    return error;
}

//upload a new product
-(void)UserUploadNewProductPic:(int)width Height:(int)height Data:(NSData*)data
{
    if (data)
    {
        self.m_UCommand = UploadImage;
        NSString *url = [NSString stringWithFormat:@"%@%d/%d", URL_UPLOADIMAGE, width, height];
        [[CDownLoadManager DefaultDownLoadManager] AddTask:url Sponsor:self PostData:data TimeOut:30 Data:[NSNumber numberWithInt:self.m_UCommand] MType:PostImage UserInfo:nil];
    }
}

-(void)UserUploadNewProduct:(NSString*)data Url:(NSString*)url Command:(UCommand)command
{
    if (data)
    {
        self.m_UCommand = UploadP;
        [[CDownLoadManager DefaultDownLoadManager] AddTask:url Sponsor:self PostData:[data dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:self.m_UCommand] MType:Post UserInfo:nil];
        NSLog(@"%@", data);
    }
}

//delegate(opretion)
-(void)DidOperationFinished:(COperation *)op Data:(NSData *)data Other:(id)other UserInfo:(id)userinfo
{
    NSString    *json = nil;
    NSDictionary *dic = nil;
    
    if (nil == other)
    {
        other = [NSNumber numberWithShort:-1];
    }
    if (nil == userinfo)
    {
        userinfo = [NSNumber numberWithShort:-1];
    }
    
    if (data)
    {
        //hearbeat
        if (HEARTBEAT == [other shortValue])
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:MSG_HEARTBEAT_RET object:data];
        }
        //register
        else if (Register == [other shortValue])
        {
            NSLog(@"<====Register====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到的注册原始数据:%@\r\n\r\n", json);
            
            id ret = nil;
            if (dic)
            {
                ret = dic;
                [self GetServerRegisterResult:dic];
            }
            else 
            {
                //json error alterview
                ret = @"注册错误,不能正确解析json";
            }
            
            [json release];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:SRV_REGISTER object:ret];
        }
        //uploadicon
        else if (UploadIcon == [other shortValue])
        {
            NSLog(@"<====UploadIcon====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            
            if (dic)
            {
                self.U_UrlIcon = [dic objectForKey:@"big"];
                
                NSLog(@"========>收到服务返回个人头像url:%@", self.U_UrlIcon);
            }
            else 
            {
                NSLog(@"========>收到服务返回个人头像url错误:%@", json);
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:SRV_USERICON object:dic];
            
            [json release];
        }
        //login
        else if (Login == [other shortValue])
        {
            NSLog(@"<====Login====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到登陆原始数据:%@\r\n\r\n", json);
            
            id ret = nil;
            if (dic)
            {
                ret = dic;
                [self GetServerLoginResult:dic];
            }
            else 
            {
                //json error alterview
                ret = @"登陆出错,不能正确解析json";
            }
            
            [json release];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:SRV_LOGIN object:ret];
        }
        //findpwd
        else if (FindPwd == [other shortValue])
        {
            NSLog(@"<====FindPwd====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到找回密码原始数据:%@\r\n\r\n", json);
            
            if (dic)
            {
                [self GetServerFindPwdResult:dic];
            }
            else 
            {
                NSLog(@"找回密码错误:%@", json);
            }
            
            [json release];
        }
        //logout
        else if (Logout == [other shortValue])
        {
            NSLog(@"<====Logout====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到登出的原始数据:%@\r\n\r\n", json);
            
            id ret = nil;
            if (dic)
            {
                ret = dic;
                [self GetServerLogoutResult:dic];
            }
            else 
            {
                //json error alterview
                ret = @"登出出错,不能正确解析json";
            }
            
            [json release];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:SRV_LOGOUT object:ret];
        }
        //ICON
        else if (0 == [other shortValue])
        {
            NSLog(@"<====ICON====>");
            
            UIImage *image = [UIImage imageWithData:data];
            if (image)
            {
                [self SaveIcon:data];
                if (m_IconView)
                {
                    m_IconView.image = [UIImage imageWithData:data];
                    m_IconView = nil;
                }
            }
            
            m_IsIconLoad = NO;
            self.m_IconOpID   = nil;
        }
        //GLastestP
        else if (GLastestP == [other shortValue])
        {
            NSLog(@"<====GLastestP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            //NSLog(@"\r\n\r\n收到最新的原始数据:%@\r\n\r\n", json);
            
            NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"最新错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GNearestP
        else if (GNearestP == [other shortValue])
        {
            NSLog(@"<====GNearestP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            //NSLog(@"\r\n\r\n收到最近的原始数据:%@\r\n\r\n", json);
            
            NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"最近错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GBestP
        else if (GBestP == [other shortValue])
        {
            NSLog(@"<====GBestP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            //NSLog(@"\r\n\r\n收到最好的原始数据:%@\r\n\r\n", json);
            
            NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"最好错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GFavoriteP
        else if (GFavoriteP == [other shortValue])
        {
            NSLog(@"<====GFavoriteP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到收藏的原始数据:%@\r\n\r\n", json);
            
            NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"收藏错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GUploadP
        else if (GUploadP == [other shortValue])
        {
            NSLog(@"<====GUploadP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到我的上传的原始数据:%@\r\n\r\n", json);
            
            NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"上传错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GSearchP
        else if (GSearchP == [other shortValue])
        {
            NSLog(@"<====GSearchP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收到搜索的原始数据:%@\r\n\r\n", json);
            
             NSArray *objects = [NSArray arrayWithObjects:other, userinfo, nil];
            
            if (dic)
            {
                [m_Target performSelector:m_Action withObject:dic withObject:objects];
            }
            else 
            {
                //json error alterview
                [m_Target performSelector:m_Action withObject:[NSDictionary dictionaryWithObjectsAndKeys:@"搜索错误,不能正确解析json", @"Msg", @"00:00:00", @"MsgTime", @"-100", @"Msg_error", nil] withObject:objects];
                NSLog(@"JsonError___%@___%@", json, data);
            }
            
            [json release];
        }
        //FavoriteP
        else if (FavoriteP == [other shortValue])
        {
            NSLog(@"========>:收到服务器收藏结果返回");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n收藏结果的原始数据:%@\r\n\r\n", json);
            
            if (dic)
            {
               [[NSNotificationCenter defaultCenter] postNotificationName:SRV_FAVORITE object:dic]; 
            }
            else 
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:SRV_FAVORITE object:nil]; 
                
                //json error alterview
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"错误" message:@"获得收藏错误,不能正确解析json" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
                [alter show];
                [alter autorelease];
            }
            
            [json release];
        }
        //UploadImage
        else if (UploadImage == [other shortValue])
        {
            NSLog(@"<====UploadImage====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n上传图片结果原始数据:%@\r\n\r\n", json);

            id ret = nil;
            if (dic)
            {
                ret = dic;
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_UPLOADIMAGE_RET object:ret];
            }
            else 
            {
                ret = json;
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_UPLOADIMAGE_RET object:ret];
            }
            
            [json release];
        }
        //UploadP
        else if (UploadP == [other shortValue])
        {
            NSLog(@"<====UploadP====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n上传美食结果的原始数据:%@\r\n\r\n", json);
            
            if (dic)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_UPLOADPRODUCT_RET object:dic];
            }
            else 
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_UPLOADPRODUCT_RET object:[NSDictionary dictionaryWithObjectsAndKeys:@"9", @"Msg_error", nil]];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //GetFrds
        else if (GetFrds == [other shortValue])
        {
            NSLog(@"<====GetFrds====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n获得好友的原始数据:%@\r\n\r\n", json);
            
            if (dic)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_GETFRDS_RET object:dic];
            }
            else 
            {
                //json error alterview
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"错误" message:@"获得好友错误,不能正确解析json" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
                [alter show];
                [alter autorelease];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:MSG_GETFRDS_RET object:[NSDictionary dictionaryWithObjectsAndKeys:@"9", @"Msg_error", nil]];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        //changeswitch
        else if (ChangeSwitch == [other shortValue])
        {
            NSLog(@"<====ChangeSwitch====>");
            
            json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            dic  = [json JSONValue];
            NSLog(@"\r\n\r\n改变通知开关结果原始数据:%@\r\n\r\n", json);
            
            if (dic)
            {
                [self ChangeSwitchResponse:dic];
            }
            else 
            {
                //json error alterview
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"错误" message:@"设置通知开关错误,不能正确解析json" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
                [alter show];
                [alter autorelease];
                NSLog(@"JsonError___%@", json);
            }
            
            [json release];
        }
        else {;}
    }
}

-(void)DidOperationError:(COperation *)op Error:(NSError *)error Other:(id)other UserInfo:(id)userinfo
{
    if (0 == [other shortValue])
    {
        NSLog(@"获得用户缩略图失败");
        m_IsIconLoad = NO;
    }
    else{;}
    
    if (nil == other)
    {
        other = [NSNumber numberWithShort:-1];
    }
    if (nil == userinfo)
    {
        userinfo = [NSNumber numberWithShort:-1];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SRV_REQUEST_ERROR object:[NSArray arrayWithObjects:other, userinfo, nil]];
}

-(void)DidOperationTimeOut:(COperation *)op Other:(id)other UserInfo:(id)userinfo
{
    if (0 == [other shortValue])
    {
        NSLog(@"获得用户缩略图超时");
        m_IsIconLoad = NO;
    }
    else {;}
    
    if (nil == other)
    {
        other = [NSNumber numberWithShort:-1];
    }
    if (nil == userinfo)
    {
        userinfo = [NSNumber numberWithShort:-1];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SRV_REQUEST_TIMEOUT object:[NSArray arrayWithObjects:other, userinfo, nil]];
}

//user opration
-(BOOL)IsEmailRight:(NSString*)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    return [emailTest evaluateWithObject:email];
}

-(unichar)IsLoginIDRight:(NSString*)strid
{
    unichar c = 'a';
    
    for (int i=0; i<[strid length]; i++)
    {
        c = [strid characterAtIndex:i];
        
        if ((c < 48) || ((c > 57) && (c < 65)) || ((c > 90) && (c < 97)) || (c > 122))
        {
            //'.','_'
            if (('.' == c) || ('_' == c))
            {
                continue;
            }
            else
            {
                return c;
            }
        }
    }
    
    return 'a';
}

-(int)CheckUserRegInput:(NSString*)name Mail:(NSString*)mail PasWd:(NSString*)paswd
{
    int nRet = 0;
    
    if (0 == [name length])
    {
        //user's name is nil
        return 257;
    }
    else if (([paswd length] < 6) && (0 == nRet))
    {
        //user's pwd is nil
        return 258;
    }
    else if ((![self IsEmailRight:mail]) || (0 == [mail length]))
    {
        return 256;
    }
    else {;}
    
    return nRet;
}

-(int)CheckUserLoginInput:(NSString*)name Mail:(NSString*)mail PasWd:(NSString*)paswd
{
    int nRet = 0;
    
    //验证登录名
    if (0 == [name length])
    {
        //user's id is nil
        nRet = 257;
    }
    //user's email is wrong
    else if ('@' == (nRet=[self IsLoginIDRight:name]))
    {
        if (![self IsEmailRight:name])
        {
            //email 
            nRet = 256;
        }
        else 
        {
            nRet = 0;
        }
    }
    else if ('a' == nRet)
    {
        nRet = 0;
    }
    else {;}
    
    //验证登陆密码
    if (([paswd length] < 6) && (0 == nRet))
    {
        //user's pwd is nil
        nRet = 258;
    }
    else {;}
    
    return nRet;
}

-(NSArray*)CheckIsNativeUser:(NSString*)key PasWd:(NSString*)paswd
{
    NSArray *user = nil;
    
    //查找该用户
    NSString *wherekey = nil;
    if ([self IsEmailRight:key])
    {
        //email
        wherekey = [NSString stringWithFormat:@"U_Mail==\"%@\"", key];
        self.U_Mail = key;
    }
    else
    {
        //name
        wherekey = [NSString stringWithFormat:@"U_Name==\"%@\"", key];
        self.U_Name = key;
    }
    self.U_Pas = paswd;
    NSArray *ret  = [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:@"Users" Keys:[NSArray arrayWithObjects:@"*", nil] Offset:0 Limit:1 Column:User_Properties_Num Condition:wherekey];
    
    //用户存在
    if ([ret count] > 0)
    {
        user = [ret objectAtIndex:0];
        m_UType = Leave;
    }
    else 
    {
        m_UType = Visitor;
    }
    
    return user;
}

-(int)UserRegister:(NSString*)name PassWord:(NSString*)pwd EMail:(NSString*)email City:(NSString*)city Nick:(NSString*)nick
{
    int nRet = [self CheckUserRegInput:name Mail:email PasWd:pwd];
    
    if (0 == nRet) 
    {
        m_UCommand = Register;
        
        self.U_Name  = name;
        self.U_Mail  = email;
        self.U_Pas   = pwd;
        self.U_City  = city;
        self.U_Nick  = nick;
        
        NSString *udid = [[UIDevice currentDevice] uniqueIdentifier];
        
        NSMutableString *des = [[NSMutableString alloc] initWithCapacity:18];
        [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
        [des appendString:@"&User_name="];
        [des appendString:name];
        [des appendString:@"&"];
        [des appendString:@"User_mail="];
        [des appendString:email];
        [des appendString:@"&"];
        [des appendString:@"User_pass="];
        [des appendString:pwd];
        [des appendString:@"&"];
        [des appendString:@"img="];
        [des appendString:self.U_UrlIcon];
        [des appendString:@"&"];
        [des appendString:@"Divtype="];
        [des appendString:[UIDevice currentDevice].model];
        [des appendString:@"&"];
        [des appendString:@"Mcode="];
        [des appendString:udid];
        [des appendString:@"&"];
        [des appendString:@"City="];
        [des appendString:self.U_City];
        
        [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_REGISTER Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:self.m_UCommand] MType:Post UserInfo:nil];
        
        [des release];
    }
    
    return nRet;
}

-(int)UserUploadIcon:(NSData*)data
{
    NSLog(@"<========上传个人头像请求");
    
    int nRet = 0;
    
    if (data)
    {
        NSString *url = [NSString stringWithFormat:@"%@%d/%d/user", URL_UPLOADIMAGE, 150, 150];
        [[CDownLoadManager DefaultDownLoadManager]AddTask:url Sponsor:self PostData:data TimeOut:30 Data:[NSNumber numberWithShort:UploadIcon] MType:PostImage UserInfo:nil];
    }
    
    return nRet;
}

-(int)UserLogin:(NSString*)name PassWord:(NSString*)pwd EMail:(NSString*)email City:(NSString*)city
{
    int nRet = [self CheckUserLoginInput:name Mail:email PasWd:pwd];
    
    //向服务器发送请求
    if (0 == nRet) 
    {
        NSArray *ret = nil;
        if ((ret = [self CheckIsNativeUser:name PasWd:pwd]))
        {
            [self SetUserWithArr:ret];
        }
        
        self.m_UCommand = Login;
        
        //NSString *udid = [[UIDevice currentDevice] uniqueIdentifier];
        
        NSMutableString *des = [[NSMutableString alloc] initWithCapacity:18];
        [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
        [des appendString:@"&user_mobi_key="];
        [des appendString:self.U_Token];
        [des appendString:@"&"];
        [des appendString:@"user_session_id="];
        [des appendString:self.U_Session];
        [des appendString:@"&"];
        [des appendString:@"Logininfo="];
        [des appendString:name];
        [des appendString:@"&"];
        [des appendString:@"op_id="];
        [des appendString:[NSString stringWithFormat:@"%ld", [self.U_AID longValue]]];
        [des appendString:@"&"];
        [des appendString:@"User_pass="];
        [des appendString:pwd];
        [des appendString:@"&"];
        [des appendString:@"Divtype="];
        [des appendString:[UIDevice currentDevice].model];
        
        NSLog(@"%@", des);
        
        [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_LOGIN Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:self.m_UCommand] MType:Post UserInfo:nil];
        
        [des release];
    }
    
    return nRet;
}

-(int)UserLogout
{
    self.m_UCommand = Logout;
        
    //向服务器发送登出
    NSMutableString *des = [[NSMutableString alloc] initWithCapacity:6];
    [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [des appendString:@"&mobikey="];
    [des appendString:self.U_Token];
    [des appendString:@"&"];
    [des appendString:@"sessionid="];
    [des appendString:self.U_Session];
    
    NSLog(@"\r\n\r\n用户%@登出:%@\r\n\r\n", self.U_Name, des);
    
    [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_LOGOUT Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:self.m_UCommand] MType:Post UserInfo:nil];
    
    [des release];
    
    return 0;
}

-(int)UserFindPwd:(NSString*)email
{
    if (![self IsEmailRight:email])
    {
        return 1;
    }
    
    //向服务器发送登出
    NSMutableString *des = [[NSMutableString alloc] initWithCapacity:1];
    [des appendFormat:@"user_email=%@", email];
    
    [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_FINDPWD Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:FindPwd] MType:Post UserInfo:nil];

    [des release];
    
    return 0;
}

-(void)GetServerFindPwdResult:(NSDictionary*)data
{
    NSLog(@"%@", [data objectForKey:@"Msg"]);
    [[NSNotificationCenter defaultCenter] postNotificationName:SRV_FINDPWD object:data];
}

-(int)UserChangeSwitchValue:(NSString*)index Value:(int)value
{
    //向服务器发送
    NSMutableString *des = [[NSMutableString alloc] initWithCapacity:8];
    [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [des appendString:@"&mobikey="];
    [des appendString:self.U_Token];
    [des appendString:@"&"];
    [des appendString:@"sessionid="];
    [des appendString:self.U_Session];
    [des appendFormat:@"&action=%@", (1 == value) ? (@"open") : (@"close")];
    [des appendFormat:@"&setName=%@", index];
    
    [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_SWITCHCHANGE Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:ChangeSwitch] MType:Post UserInfo:nil];
    
    [des release];
    
    return 0;
}

-(void)ChangeSwitchResponse:(NSDictionary*)dic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:MSG_CHANGESWITCH_RET object:dic];
}

-(void)GetServerLogoutResult:(NSDictionary*)data
{
    //int nCode = [[data objectForKey:@"Msg_error"] intValue];
    NSLog(@"%@", [data objectForKey:@"Msg"]);
    if (1)
    {
        CKey *key = [[CKey alloc] initWithType:1 Value:[NSNumber numberWithLong:0] Name:@"U_LogIn"];
        NSArray *keys = [NSArray arrayWithObjects:key, nil];
        [key release];
        
        [CUser UpadteUserInfo:[NSString stringWithFormat:@"U_AID == %ld", [self.U_AID longValue]] Keys:keys];
        [self ResetUser];
    }
    
    [self StopHeartBeat];
}

//save upload
-(void)SaveUpload:(CProduct*)product
{
    if (Logined == m_UType)
    {
        product.P_Icon  = [NSString stringWithFormat:@"%@/%lld_icon.jpg", m_UploadPath, [product.P_AID longLongValue]];
        product.P_Image = [NSString stringWithFormat:@"%@/%lld_image.jpg", m_UploadPath, [product.P_AID longLongValue]];
        
        [product SaveProduct:m_UploadTable];
    }
}

//save favorite
-(int)SaveFavorite:(CProduct*)product
{
    if (Logined == m_UType)
    {
        CLike *like = [[CLike alloc] initWithProduct:product];
        
        int nRet = [like SaveLike:m_FavoriteTable IconPath:m_FavoritePath ImagePath:m_FavoritePath];
        [like release];
        
        return nRet;
    }
    
    return 1;
}

@end
